<?php
namespace App\Wen\Utils;

use App\Jobs\CalculateCommentLikesNumJob;
use App\Jobs\SubscribeMessageJob;
use App\Jobs\System\CheckBatchCahceDataLossJob;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\WxCommentLike;
use App\Models\User\WxUser;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class CommentUtils{
    public static $ad_config = null;

    public static function comment_process($k, $v, $posts_id, $post_user_id, $uid = 0, $style = -1, $scene = 0){
        Redis::sadd('robot:timed:comment:active', $v->id);
        // $scene 暂时分不了
        $imgList = array();
        $v->comment_img_url = Utils::imgWithStyle($v->comment_img_url);
        array_push($imgList, ['img_url' => $v->comment_img_url]);
        $v->user = UserUtils::get_cached_user($v->user_id);
        $v->is_like = WxCommentLike::where('comment_id', $v->id)->where('user_id', $uid)
            ->exists();
        $v->like_count = WxCommentLike::where('comment_id', $v->id)->count();
        $v->imgList = $imgList;
        $v->comment_content_raw = strip_tags( _mini_phone( _mini_emoji(_mini_aite_replace($v->comment_content, true), true), true));

        $allowable = [];
        if($uid > 0){
            if(UserUtils::is_mini_admin($uid) || $v->posts_user_id == $uid){
                if($v->is_sticky){
                    $allowable[] = [
                        'text' => '取消置顶',
                        'type' => 'unsticky',
                        'id' => $v->id,
                        'icon' => 'mini-icon mini-zhiding1'
                    ];
                }else{
                    $allowable[] = [
                        'text' => '置顶',
                        'type' => 'sticky',
                        'id' => $v->id,
                        'icon' => 'mini-icon mini-zhiding1'
                    ];
                }

            }
            if($uid != $v->user_id){
                $allowable[] = [
                    'text' => '举报',
                    'type' => 'report',
                    'id' => $v->id,
                    'icon' => 'mini-icon mini-jinggao'
                ];
            }

            if($uid == $v->user_id || UserUtils::is_mini_admin($uid)){
                $allowable[] = [
                    'text' => '删除',
                    'type' => 'delete',
                    'id' => $v->id,
                    'icon' => 'mini-icon2 mini-shanchu'
                ];
            }
        }
        $allowable[] = [
            'text' => '复制',
            'type' => 'copy',
            'id' => $v->id,
            'raw' => $v->comment_content_raw,
            'icon' => 'mini-icon mini-fuzhi'
        ];
        $v->allowable = $allowable;
        $v->child_current_max_id = 0;
        $v->child_total_max_id = 0;

        if($v->user_id != $post_user_id){
            $v->is_author_liked = WxCommentLike::where('user_id', $post_user_id)->where('comment_id', $v->id)->exists();
        }else{
            $v->is_author_liked = false;
        }

        $child_num = Settings::get('sticky_comments_child_num', 10, true);
        if($child_num > 0){
            $childData = WxComment::where('comment_id', $v->id)->where('comment_state', 1)->orderBy('id', 'asc')->limit($child_num)->get(FieldUtils::commentInfoColums());
            if($childData){
                $childData->map(function ($item) use ($uid, &$v, $post_user_id) {
                    if($item->id > $v->child_current_max_id){
                        $v->child_current_max_id = $item->id;
                    }
                    $imgList = array();
                    $item->comment_img_url = Utils::imgWithStyle($item->comment_img_url);
                    if($item->comment_img_url){
                        array_push($imgList, ['img_url' => $item->comment_img_url]);
                    }

                    $item->is_like = WxCommentLike::where('comment_id', $item->id)->where('user_id', $uid)->exists();
                    $item->like_count = WxCommentLike::where('comment_id', $item->id)->count();
                    $item->imgList = $imgList;
                    $item->user = UserUtils::get_cached_user($item->user_id);
                    $item->comment_content_raw = strip_tags( _mini_phone( _mini_emoji(_mini_aite_replace($item->comment_content, true), true), true));
                    $sub_allowable = [];
                    if($uid > 0){
                        if($uid != $item->user_id) {
                            $sub_allowable[] = [
                                'text' => '举报',
                                'type' => 'report',
                                'id' => $item->id,
                                'icon' => 'mini-icon mini-jinggao'
                            ];
                        }
                        if($uid == $item->user_id || UserUtils::is_mini_admin($uid)){
                            $sub_allowable[] = [
                                'text' => '删除',
                                'type' => 'delete',
                                'id' => $item->id,
                                'icon' => 'mini-icon2 mini-shanchu'
                            ];
                        }
                    }
                    $sub_allowable[] = [
                        'text' => '复制',
                        'type' => 'copy',
                        'id' => $item->id,
                        'raw' => $item->comment_content_raw,
                        'icon' => 'mini-icon mini-fuzhi'
                    ];
                    $item->allowable = $sub_allowable;
                    if($item->user_id != $post_user_id) {
                        $item->is_author_liked = WxCommentLike::where('user_id', $post_user_id)->where('comment_id', $item->id)->exists();
                    }else{
                        $item->is_author_liked = false;
                    }
                    self::anonymousProcess($item);
                });
                if($v->child_current_max_id > 0){
                    if($childData->count() == $child_num){
                        $v->child_total_max_id = WxComment::where('comment_id', $v->id)->where('comment_state', 1)->orderBy('id', 'desc')->value('id');
                    }else{
                        $v->child_total_max_id = $v->child_current_max_id;
                    }
                }
            }

            $childData->append(['format_time', 'ip_address']);
            $v->child = $childData;
        }else{
            $v->child = [];
        }

        self::anonymousProcess($v);

        $v->child_page = 1;
        $v->child_loading = false;

        if($v->child_total_max_id == $v->child_current_max_id){
            $v->child_is_last_page = true;
        }else{
            $v->child_is_last_page = false;
        }

        if(($k + 1) % 6 === 0){
            self::get_ad($v);
        }else{
            $v->ad = null;
        }


        return $v;
    }


    public static function anonymousProcess(&$comment){
        if($comment->is_anonymous == 1){
            $comment->user_id = -1 * $comment->user['id'];
            $comment->user_name = $comment->user['anonymous_name'] ?? '匿名';
            $comment->user_avatar = $comment->user['anonymous_avatar'] ?? Settings::get('img_default_avatar', '');
            if($comment->user){
                $comment->user = [
                    'id' => -1 * ($comment->user['id'] ?? 1),
                    'user_name' => $comment->user['anonymous_name'] ?? '匿名',
                    'user_avatar' => ($comment->user['anonymous_avatar'] ?? Settings::get('img_default_avatar', '')).'?imageMogr2/thumbnail/100x100/crop/100x100/gravity/center/format/webp/interlace/1/quality/100',
                    'setting' => [
                        'privacy_get_my_wechat' => 4,
                        'privacy_get_my_wechat_pay' => 0,
                        'privacy_get_my_phone' => 4,
                        'privacy_get_my_phone_pay' => 0,
                        'teenage_mode_state' => 0,
                    ]
                ];
            }
        }
    }


    private static function get_ad(&$v){
        global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_PAYCODE_14__;
        if(!$__MINI_GLOBAL_PAYCODE_14__){
            return;
        }
        if(mini_current_user(1) && Settings::get('app_vip_ad_shut', 0) == 1){
            return;
        }
        //广告
        if(self::$ad_config === null){
            self::$ad_config = json_decode(Cache::get(_multi_key('ad_config'), '[]'), true);
            if(_empty_(self::$ad_config)){
                CheckBatchCahceDataLossJob::dispatch();
            }
        }
        if(self::$ad_config){
            // 评论推流
            if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                if(self::$ad_config['mp']['position3']['flow']){
                    $v->ad = _array_rand_element(self::$ad_config['mp']['position3']['flow']);
                }
            }else{
                if(self::$ad_config['uni']['position3']['flow']){
                    $v->ad = _array_rand_element(self::$ad_config['uni']['position3']['flow']);
                }
            }
        }
    }

    public static function get_comment_post_author($comment_id){
        if(_empty_($comment_id)){
            return 0;
        }
        $posts_user_id = WxComment::where('id', $comment_id)->value('posts_user_id');
        if($posts_user_id){
            return $posts_user_id;
        }
        return 0;
    }

    public static function get_comment_user($comment_id){
        if(_empty_($comment_id)){
            return 0;
        }
        $user_id = WxComment::where('id', $comment_id)->value('user_id');
        if($user_id){
            return $user_id;
        }
        return 0;
    }

    public static function comment_like($uid,  $comment_id){
        if(_empty_($uid) || _empty_($comment_id)){
            return 0;
        }
        $post_id = WxComment::where('id', $comment_id)->value('posts_id');
        $post = WxPost::where('id', $post_id)->first(['user_id', 'circle_id']);
        $post_user_id = $post->user_id;
        $circle_id = $post->circle_id;

        $comment_user_id = WxComment::where('id', $comment_id)->value('user_id');


        $likeIsExists = WxCommentLike::where('user_id',$uid)
            ->where('comment_id',$comment_id)
            ->where('comment_user_id',$comment_user_id)->exists();
        // 判断是否已经点过赞
        if($likeIsExists){
            WxCommentLike::where('user_id',$uid)
                ->where('comment_id',$comment_id)
                ->where('comment_user_id',$comment_user_id)->delete();
            Cache::forget('user:beliked:count:'.$comment_user_id);
            return 2;
        }


        $CommentLikeModel = new WxCommentLike();
        $CommentLikeModel->user_id = $uid;
        $CommentLikeModel->comment_id = $comment_id;
        $CommentLikeModel->comment_user_id = $comment_user_id;
        $CommentLikeModel->save();


        $user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
        $comment = WxComment::where('id', $comment_id)->first();

        UserUtils::add_user_experience($uid, 5);
        if(!$likeIsExists){
            Redis::sadd('realtime:others:set', json_encode([$comment_user_id, 4, 1]));
            Redis::sadd('realtime:others:set', json_encode([$post_id, 1, 1]));
            Redis::sadd('realtime:others:set', json_encode([$post_user_id, 4, 1]));
            Redis::sadd('realtime:others:set', json_encode([$circle_id, 2, 1]));
        }
        if($comment_user_id != $user['id']){
            UserUtils::add_user_notice(3003, $comment_user_id, '您的评论收到了一个喜欢', '「<a href="/pages/user/user?id='.$user['id'].'">'.$user['user_name'].'</a>」' . '喜欢了您的评论。', 101, $comment['posts_id']);
        }
        Cache::forget('user:beliked:count:'.$comment_user_id);
        update_user_visit($user['id'], 1, $post_id);
        return 1;
    }

    public static function comment_pass(WxComment &$comment, $flag = 1, $overrule_content = ''){
        $posts_id = $comment->posts_id;
        $is_need_notice = false;
        if($comment->comment_state === 0){
            $is_need_notice = true;
        }
        if($flag == 1){
            WxComment::where('id', $comment->id)->update(['comment_state'=>1]);
            if($is_need_notice){
                $msg = UserUtils::reward_user_coin($comment->user_id, 'comment');
                if($msg){
                    GatewayUtils::info_message(GatewayUtils::uid2client_id($comment->user_id), '恭喜，获得评论奖励：'.$msg);
                    UserUtils::assistant_notice($comment->user_id, '您的评论(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$comment->id.'</a>)审核已通过，并获得评论奖励：'.$msg);
                }else{
                    UserUtils::assistant_notice($comment->user_id, '您的评论(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$comment->id.'</a>)审核已通过');
                }

                if($comment->user_id != $comment->posts_user_id){
                    if($comment->is_anonymous == 1){
                        $the_comment_user = WxUser::find($comment->user_id);
                        $anonymous = UserUtils::get_anonymous_info($the_comment_user);
                        if($anonymous){
                            UserUtils::add_user_notice(3002, $comment->posts_user_id, '你的评论收到了一个回复快去看看吧', '「<a href="/pages/user/user?id=-'.$comment->user_id.'">'.$anonymous['anonymous_name'].'</a>' . '」回复了您的评论。', 102, $posts_id);
                        }
                    }else{
                        UserUtils::add_user_notice(3002, $comment->posts_user_id, '你的评论收到了一个回复快去看看吧', '「<a href="/pages/user/user?id='.$comment->user_id.'">'.$comment->user_name.'</a>' . '」回复了您的评论。', 102, $posts_id);
                    }
                }
                _mini_aite($comment->user_id, $comment->comment_content, 2, true, $posts_id, $comment->id);

                CalculateCommentLikesNumJob::dispatch($comment->id);
                if($comment->comment_id && $comment->comment_id > 0){
                    CalculateCommentLikesNumJob::dispatch($comment->comment_id);
                }

                SubscribeMessageJob::dispatch('comment_add', $comment->id);
                if($comment->comment_id > 0){
                    SubscribeMessageJob::dispatch('comment_reply', $comment->id);
                }
            }
            Cache::forget('post:commentCount:'.$posts_id);
        }else if($flag == 2){
            WxComment::where('id', $comment->id)->update(['comment_state'=>2]);
            $popular_comment = json_decode(Cache::get('post:popular:comment:'.$posts_id, '[]'), true);
            if(_array_key($popular_comment, 'id', 0) == $comment->id){
                Cache::forget('post:popular:comment:'.$posts_id);
                Redis::sadd('post:popular:comment:set', $posts_id);
            }
            UserUtils::assistant_notice($comment->user_id, '您的评论(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$comment->id.'</a>)审核已驳回');
        }
        Cache::forget('total:todo:count');
        Cache::forget('total:tenant:todo:count');
    }


 /**
     * 根据 comment_id 获取评论详情，并进行数据处理
     *
     * @param int $comment_id 评论的 ID
     * @param int $uid 当前用户 ID（默认为 0）
     * @param int $post_user_id 帖子作者的 ID
     * @return array|null 返回处理后的评论详情，失败返回 null
     */
    public static function getCommentByCommentId($comment_id, $uid = 0, $post_user_id)
    {
        // 获取单条评论记录
        $comment = WxComment::where('id', $comment_id)
            ->first();

        if (!$comment) {
            return null;
        }
            // 格式化评论信息
            $comment->comment_img_url = Utils::imgWithStyle($comment->comment_img_url); // 处理图片
            $comment->user = UserUtils::get_cached_user($comment->user_id); // 获取用户信息
            $comment->is_like = WxCommentLike::where('comment_id', $comment_id)->where('user_id', $uid)->exists(); // 用户是否点赞
            $comment->like_count = WxCommentLike::where('comment_id', $comment_id)->count(); // 点赞数量
            $comment->comment_content_raw = strip_tags(_mini_phone(_mini_emoji(_mini_aite_replace($comment->comment_content, true), true), true)); // 处理评论内容

            // 允许的操作
            $allowable = [];
            if ($uid == $comment->user_id) {
                $allowable[] = [
                    'text' => '删除',
                    'type' => 'delete',
                    'id' => $comment->id,
                    'icon' => 'mini-icon2 mini-shanchu'
                ];
            }
            $allowable[] = [
                'text' => '复制',
                'type' => 'copy',
                'id' => $comment->id,
                'raw' => $comment->comment_content_raw,
                'icon' => 'mini-icon mini-fuzhi'
            ];
            $comment->allowable = $allowable;

            // 返回评论信息
            return $comment;
        
        }
}